﻿#coding: utf-8

require 'sinatra/jsonp'

# Read
get '/content/:id' do
	c = Content.get(params[:id])
	if c.nil? then
		404
	else
		res = c.to_json
		if params[:format] == 'js' then
			JSONP res
		else
			body(res)
			200
		end
	end
end

# Delete
delete '/content/:id' do
	content = Content.get(params[:id])
	if content != nil then
		if content.destroy then
			200
		else
			400
		end
	else
		404
	end
end

# Add
put '/content' do
	puts request.body.string
	begin
		data = JSON.parse(request.body.string)
	rescue JSON::ParserError
		400
	end
	if data.nil? or !data.has_key?('node_id') then
		400
	else
		c = Content.create(
			:text => data['text'],
			:movie => data['movie'],
			:music => data['music'],
			:image => data['image'],
			:qrcode => data['qrcode'],
			:lat => data['lat'],
			:long => data['long'],
			:street => data['street'],
			:postal_code => data['postal_code'],
			:town => data['town'],
			:phone => data['phone'],
			:history => data['history'],
			:website => data['website'],			
			:created_at => Time.now,
			:updated_at => Time.now,
			:node_id => data['node_id']
		)
		
		c.save
		body(c.id.to_s)
		200
	end
end

# Update
put '/content/:id' do
	puts request.body.string
	begin
		data = JSON.parse(request.body.string)
	rescue JSON::ParserError
		400
	end
		content = Content.get(params[:id])
	if content != nil then
		
		if data.has_key?('text') then
			content.update(:text => data['text'])
		end
		if data.has_key?('movie') then
			content.update(:movie => data['movie'])
		end
		if data.has_key?('music') then
			content.update(:music => data['music'])
		end
		if data.has_key?('image') then
			content.update(:image => data['image'])
		end
		if data.has_key?('qrcode') then
			content.update(:qrcode => data['qrcode'])
		end
		if data.has_key?('lat') then
			content.update(:lat => data['lat'])
		end
		if data.has_key?('long') then
			content.update(:long => data['long'])
		end
		if data.has_key?('street') then
			content.update(:street => data['street'])
		end
		if data.has_key?('postal_code') then
			content.update(:postal_code => data['postal_code'])
		end
		if data.has_key?('town') then
			content.update(:town => data['town'])
		end
		if data.has_key?('phone') then
			content.update(:phone => data['phone'])
		end
		if data.has_key?('history') then
			content.update(:history => data['history'])
		end
		if data.has_key?('website') then
			content.update(:website => data['website'])
		end
		
		content.update(:updated_at => Time.now)
		
		content.save
		body(content.id.to_s)
		200
	else
		404
	end
end
